package com.emep.changzhi.analyse.service.aqi;

import com.emep.changzhi.analyse.entity.aqi.AqiControlInfo;
import com.emep.changzhi.analyse.model.AqiControllerData;
import com.emep.changzhi.analyse.repository.aqi.AqiControlInfoRepository;
import com.emep.changzhi.analyse.utils.DateTimeUtil;
import com.emep.changzhi.analyse.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.text.ParseException;
import java.util.*;

/**
 * @author wangcc
 * @version V1.0
 * @Description: 管控业务层
 * @date 2018/3/28  14:15
 */
@Service
@Slf4j
public class AqiControlInfoService {


    @Resource
    private AqiControlInfoRepository aqiControlInfoRepository;

//统计不同站点，不同污染物当前时间的值或者选定时间，和前一小时、前一天、上个月同时间值比较的百分比
    public AqiControllerData findAqiControlInfo( Map<String, Object> payload) {
        AqiControllerData aqiControllerData = new AqiControllerData();

        //监测站名字
        String siteName = payload.get("siteName") != null ? payload.get("siteName").toString():"" ;
        //返回值类型
        String returnPararm = payload.get("returnPararm")!= null ? payload.get("returnPararm").toString():"";
        //时间
        String time = payload.get("time")!= null ? payload.get("time").toString():"";
        //因子名字
        String pollutionName = payload.get("pollutionName")!= null ? payload.get("pollutionName").toString():"";

        //当前时间
        Date currentTime = null;
        try {
            currentTime = DateTimeUtil.stringToDate(time,DateTimeUtil.DATETIME_DEFAULT_FORMAT);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //获取当前时间对象
      AqiControlInfo a=  aqiControlInfoRepository.findByPollutantAndPositionNameAndTimePoint(aqiControllerData.getSiteName() , aqiControllerData.getPollutionName() , currentTime+"");


        //
        AqiControlInfo info=new AqiControlInfo();
        //pre-day,pre-hour,per-month
        switch (returnPararm){
            case "pre-day":
                //获取前一天数据
                Date preDay = DateTimeUtil.mathDate(currentTime ,-1 , Calendar.DAY_OF_MONTH);
                info = aqiControlInfoRepository.findByPollutantAndPositionNameAndTimePoint(aqiControllerData.getSiteName() , aqiControllerData.getPollutionName() , preDay.getTime()+"");

                break;
            case "pre-hour":
                //获取前一小时数据

                Date preHour = DateTimeUtil.mathDate(currentTime ,-1 , Calendar.HOUR);
                 info = aqiControlInfoRepository.findByPollutantAndPositionNameAndTimePoint(aqiControllerData.getSiteName() , aqiControllerData.getPollutionName() , preHour.getTime()+"");

                break;
            case "per-month":
                //获取上月数据
                Date preMonth = DateTimeUtil.mathDate(currentTime ,-1 , Calendar.DAY_OF_MONTH);
                info = aqiControlInfoRepository.findByPollutantAndPositionNameAndTimePoint(aqiControllerData.getSiteName() , aqiControllerData.getPollutionName() , preMonth.getTime()+"");

                break;

        }
        //计算百分比
        String hundred="-";
        if(info!=null){
            String strhour = (((Float.parseFloat(a.getPollutantData()) - Float.parseFloat(info.getPollutantData()))/Float.parseFloat(a.getPollutantData()))*100)+"";
            aqiControllerData.setPreHour(String.format("%.0f", Float.parseFloat(strhour))+"%");
            hundred=String.format("%.0f", Float.parseFloat(strhour))+"%";
        }

        aqiControllerData.setSiteName(siteName);
        aqiControllerData.setTime(time);
        aqiControllerData.setPollutionName(pollutionName);
        switch (returnPararm){
            case "pre-day":
                aqiControllerData.setPreDay("pre-day:"+hundred);
                break;
            case "pre-hour":
                aqiControllerData.setPreHour("pre-hour:"+hundred);
                break;
            case "per-month":
                aqiControllerData.setPreHour("pre-month:"+hundred);
                break;

        }
        aqiControllerData.setValue(a.getPollutantData());
        aqiControllerData.setMaxValue(a.getStandard());
        return aqiControllerData;

    }


    /**
     *
     * @param
     * @return
     */
    public List<AqiControllerData> findAqiControlInfoByAreaIdAndTimePoint(String positionName,String timePoint,String pollutant){
        List<AqiControlInfo> aqiControlInfos = new ArrayList<AqiControlInfo>();


        /**
         * 什么都不传查询所有站点所有污染物近2个月记录
         */
        if(StringUtils.isEmpty(timePoint) && StringUtils.isEmpty(positionName) && StringUtils.isEmpty(pollutant)){
            Sort sort = new Sort(Sort.Direction.DESC, "timePoint");
            aqiControlInfos = aqiControlInfoRepository.findAll(new Specification<AqiControlInfo>(){
                @Override
                public javax.persistence.criteria.Predicate toPredicate(Root<AqiControlInfo> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                    //大于或等于传入时间
                    javax.persistence.criteria.Predicate p1 = criteriaBuilder.greaterThanOrEqualTo(root.get("timePoint").as(String.class), String.valueOf(DateTimeUtil.mathNowMothOfDate(-2).getTime()));
                    //小于或等于传入时间
                    javax.persistence.criteria.Predicate p2 = criteriaBuilder.lessThanOrEqualTo(root.get("timePoint").as(String.class), String.valueOf(System.currentTimeMillis()));
                    query.where(criteriaBuilder.and(p1,p2));
                    return query.getRestriction();
                }
            },sort);


        }
        //传入污染物和站点
        if(!StringUtils.isEmpty(pollutant) && !StringUtils.isEmpty(positionName)){
            Sort sort = new Sort(Sort.Direction.DESC, "timePoint");
            aqiControlInfos = aqiControlInfoRepository.findAll(new Specification<AqiControlInfo>(){
                @Override
                public javax.persistence.criteria.Predicate toPredicate(Root<AqiControlInfo> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                    //站点
                    javax.persistence.criteria.Predicate p3 = criteriaBuilder.equal(root.get("positionName").as(String.class), positionName);
                    //因子名字
                    javax.persistence.criteria.Predicate p4 = criteriaBuilder.equal(root.get("pollutant").as(String.class), pollutant);
                    //大于或等于传入时间
                    javax.persistence.criteria.Predicate p1 = criteriaBuilder.greaterThanOrEqualTo(root.get("timePoint").as(String.class), String.valueOf(DateTimeUtil.mathNowMothOfDate(-2).getTime()));
                    //小于或等于传入时间
                    javax.persistence.criteria.Predicate p2 = criteriaBuilder.lessThanOrEqualTo(root.get("timePoint").as(String.class), String.valueOf(System.currentTimeMillis()));
                    query.where(criteriaBuilder.and(p1,p2,p3,p4));
                    return query.getRestriction();
                }
            },sort);
        }
        //污染物和站点以及今天0点到24点的数据
       if(StringUtils.isEmpty(pollutant) && StringUtils.isEmpty(positionName) && !StringUtils.isEmpty(timePoint)){
           Sort sort = new Sort(Sort.Direction.DESC, "timePoint");
           aqiControlInfos = aqiControlInfoRepository.findAll(new Specification<AqiControlInfo>(){
               @Override
               public javax.persistence.criteria.Predicate toPredicate(Root<AqiControlInfo> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                   javax.persistence.criteria.Predicate p1 = null;
                   javax.persistence.criteria.Predicate p2 = null;
                   try {
                       //大于或等于传入时间
                       p1 = criteriaBuilder.greaterThanOrEqualTo(root.get("timePoint").as(String.class), DateTimeUtil.getStartDate(timePoint));
                       //小于或等于传入时间
                       p2 = criteriaBuilder.lessThanOrEqualTo(root.get("timePoint").as(String.class), DateTimeUtil.getEndDate(timePoint));
                   } catch (ParseException e) {
                       e.printStackTrace();
                   }
                   query.where(criteriaBuilder.and(p1,p2));
                   return query.getRestriction();
               }
           },sort);
       }
        List<AqiControllerData> aqiControllerDataList = contrastData(aqiControlInfos);

        return aqiControllerDataList;
    }


    /**
     * 前一小时，前一天，上月
     * */
    public List<AqiControllerData> contrastData(List<AqiControlInfo> aqiControlInfos){
        List<AqiControllerData> aqiControllerDataList = new ArrayList<AqiControllerData>();
        for(AqiControlInfo controller : aqiControlInfos){
            AqiControllerData aqidata = new AqiControllerData();
            aqidata.setId(controller.getId());
            aqidata.setSiteName(controller.getPollutant());
            aqidata.setPollutionName(controller.getPositionName());
            aqidata.setValue(controller.getPollutantData());
            aqidata.setTime(controller.getTimePoint());
            //获取timepoint监测时间
            String timepoint = controller.getTimePoint();
            aqidata = contrast(timepoint , controller.getPollutantData() , aqidata);
            aqidata.setMaxValue(controller.getStandard());
            aqidata.setTips(controller.getStatus());
            aqiControllerDataList.add(aqidata);
        }
        return aqiControllerDataList;
    }

    public AqiControllerData contrast(String time , String data , AqiControllerData aqiControllerData){
        //获取前一小时数据
        Date currentTime = DateTimeUtil.stampToDate(time);
        Date preHour = DateTimeUtil.mathDate(currentTime ,-1 , Calendar.HOUR);
        AqiControlInfo info1 = aqiControlInfoRepository.findByPollutantAndPositionNameAndTimePoint(aqiControllerData.getSiteName() , aqiControllerData.getPollutionName() , preHour.getTime()+"");
        //获取前一天数据
        Date preDay = DateTimeUtil.mathDate(currentTime ,-1 , Calendar.DAY_OF_MONTH);
        AqiControlInfo info2 = aqiControlInfoRepository.findByPollutantAndPositionNameAndTimePoint(aqiControllerData.getSiteName() , aqiControllerData.getPollutionName() , preDay.getTime()+"");
        //获取上月数据
        Date preMonth = DateTimeUtil.mathDate(currentTime ,-1 , Calendar.DAY_OF_MONTH);
        AqiControlInfo info3 = aqiControlInfoRepository.findByPollutantAndPositionNameAndTimePoint(aqiControllerData.getSiteName() , aqiControllerData.getPollutionName() , preMonth.getTime()+"");
        if(info1!=null){
            String strhour = (((Float.parseFloat(data) - Float.parseFloat(info1.getPollutantData()))/Float.parseFloat(data))*100)+"";
            aqiControllerData.setPreHour(String.format("%.0f", Float.parseFloat(strhour))+"%");
        }else{
            aqiControllerData.setPreHour("-");
        }
        if(info2!=null){
            String strday = (((Float.parseFloat(data) - Float.parseFloat(info2.getPollutantData()))/Float.parseFloat(data))*100)+"";
            aqiControllerData.setPreDay(info2==null ? "-" : String.format("%.0f", Float.parseFloat(strday))+"%");
        }else{
            aqiControllerData.setPreDay("-");
        }
        if(info3!=null){
            String strmonth = (((Float.parseFloat(data) - Float.parseFloat(info3.getPollutantData()))/Float.parseFloat(data))*100)+"";
            aqiControllerData.setPreMonth(info3==null ? "-" : String.format("%.0f", Float.parseFloat(strmonth))+"%");
        }else{
            aqiControllerData.setPreMonth("-");
        }
        return aqiControllerData;
    }

}
